import requests
import time
from threading import Thread
import requests
import json
import time
import datetime
import argparse


def send_request(url, method, headers, params):
    try:
        if method.lower() == 'get':
            response = requests.get(url, headers=headers, params=params)
        elif method.lower() == 'post':
            response = requests.post(url, headers=headers, json=params)
        else:
            print(f'不支持的请求方法: {method}')
            return

        print(f'状态码: {response.status_code}, 响应内容: {response.text}')
    except Exception as e:
        print(f'请求发生错误: {e}')


def start_sending_requests(url, method, headers, params, requests_per_second, duration):
    end_time = time.time() + duration
    while time.time() < end_time:
        send_request(url, method, headers, params)
        time.sleep(1 / requests_per_second)


def send_http_request(url, interval, count):
    for i in range(count):
        # 获取当前请求时间
        request_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        payload = {'request_time': request_time}

        # 发送 HTTP POST 请求
        response = requests.post(url, json=payload)

        # 获取响应时间
        response_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        print(f"Request {i + 1}:")
        print(f"  Request Time: {request_time}")
        print(f"  Response Time: {response_time}")
        print(f"  Response Status Code: {response.status_code}")
        if response.status_code == 200:
            print(f"  Response Body: {response.text}")
        print('-' * 40)

        # 等待指定的间隔时间
        time.sleep(interval)


if __name__ == "__main__":
    url = 'http://10.10.1.53:8000/test/c1/anything'
    count = 100
    interval = 0.1

    send_http_request(url, interval, count)
    parser = argparse.ArgumentParser(description='Send HTTP requests with current request time in the payload.')
    parser.add_argument('--url', type=str, required=True, help='The URL to send HTTP requests to.')
    parser.add_argument('--count', type=int, default=1, help='Number of requests to send.')
    parser.add_argument('--interval', type=float, default=1.0, help='Interval between requests in seconds.')

    args = parser.parse_args()

    send_http_request(args.url, args.interval, args.count)

# if __name__ == "__main__":
#     # 自定义请求参数
#     url = "http://10.10.1.38:8000/test/anything"  # 替换为您的请求地址
#     method = "POST"  # 或 "POST"
#     headers = {
#         "Content-Type": "application/json",  # 可自定义请求头
#     }
#     params = {}  # 可自定义查询参数
#
#     requests_per_second = 1  # 每秒发送次数
#     duration = 1  # 持续时间（秒）
#
#     # 启动请求发送
#     print(f'开始发送请求，每秒 {requests_per_second} 次，持续 {duration} 秒')
#     start_sending_requests(url, method, headers, params, requests_per_second, duration)
